/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        int res = INT_MIN;
        maxFromHere(root, res);
        return res;
    }
    
private:
    // maxPathSum within the subtree of the input node & end at the input node
    int maxFromHere(TreeNode* root, int& result) {
        if (!root)
            return 0;
        int leftSub = max(maxFromHere(root -> left, result), 0);
        int rightSub = max(maxFromHere(root -> right, result), 0);
        result = max(result, leftSub + rightSub + root -> val);
        return max(leftSub, rightSub) + root -> val;
    }
};
